import express from "express";
import sharp from "sharp";
import path from "node:path";
import Result from "../../common/result.js";
import fse from "fs-extra";
import { UPLOAD_PATH } from "../../const/index.js";
import { getImageType } from "../../utils/file.js";

const imageRouter = express.Router();

imageRouter.post("/convert", async (req, res) => {
  try {
    const { fileHash, fileName, targetFormat } = req.body;
    const filePath = path.join(
      UPLOAD_PATH,
      `${fileHash}${path.extname(fileName)}`
    );
    if (!fse.existsSync(filePath)) {
      return res.status(101).send(Result.error("文件不存在", "转换失败", 101));
    }
    const result = await sharp(filePath)[targetFormat]().toBuffer();
    await res.status(200).send(result);
    fse.remove(filePath);
  } catch (error) {
    return res
      .status(101)
      .send(Result.error({ error }, "转换失败，发生了未知错误", 101));
  }
});

imageRouter.post("/compress", async (req, res) => {
  try {
    const { fileHash, fileName, compressLevel } = req.body;
    const filePath = path.join(
      UPLOAD_PATH,
      `${fileHash}${path.extname(fileName)}`
    );
    if (!fse.existsSync(filePath)) {
      return res.status(101).send(Result.error("文件不存在", "压缩失败", 101));
    }
    const data = await sharp(filePath)
      [getImageType(fileName)]({
        quality: 100 - compressLevel * 10,
      })
      .toBuffer();
    await res.status(200).send(data);
    fse.remove(filePath);
  } catch (error) {
    return res
      .status(101)
      .send(Result.error({ error }, "压缩失败，发生了未知错误", 101));
  }
});

export default imageRouter;
